import { FileImageOutlined, MoreOutlined, PlusCircleOutlined } from '@ant-design/icons'
import React, { useEffect, useState } from 'react'
import { useAppDispatch, useAppSelector } from '../../../hooks/store'
import { categoryIdChange, createCategory, deleteCategory, fetchCategories, updateCategory } from '../../../store/slice/category'
import { useSearchParams } from 'react-router-dom'
import UserMenuItem, { AppMenuItemAction } from './UserMenuItem'
import UserMenu from './UserMenu'
import CategoryFormModal from './CategoryFormModal'
import { CreateCategoryRequest, UpdateCategoryRequest } from '../../../api/category'
import { Modal } from 'antd'
import { detailReset } from '../../../store/slice/picture'

const UserCategoryMenu:React.FC = () => {
    const [searchParams, setSearchParams] = useSearchParams()
    const dispatch = useAppDispatch()
    const categoryState = useAppSelector((state) => state.category)
    const [createFormOpen, setCreateFormOpen] = useState<boolean>(false)
    const [updateFormOpen, setUpdateFormOpen] = useState<boolean>(false)
    const [deleteFormOpen, setDeleteFormOpen] = useState<boolean>(false)
    const [initialValues, setinitialValues] = useState<Partial<UpdateCategoryRequest>>()
    const items = categoryState.list.map((c) => ({
        key: c.id.toString(),
        icon: <FileImageOutlined />,
        label: c.name,
    }))
    const actions: AppMenuItemAction[] = [
        { label: '编辑', onClick: () => { setUpdateFormOpen(true) } },
        { label: '删除', onClick: () => { setDeleteFormOpen(true) }, danger: true }
    ]
    const onCreate = (values: CreateCategoryRequest) => {
        dispatch(createCategory(values))
        setCreateFormOpen(false)
    }
    const onUpdate = (values: UpdateCategoryRequest) => {
        values.id = Number(categoryState.current)
        dispatch(updateCategory(values))
        setUpdateFormOpen(false)
    }
    const onDelete = () => {
        dispatch(deleteCategory({ id: Number(categoryState.current) }))
        setDeleteFormOpen(false)
    }
    useEffect(() => {
        if (categoryState.status === 'idle') {
            dispatch(fetchCategories())
        } else if (categoryState.status === 'succeeded') {
            const selectedCategory = categoryState.list.find((c) => c.id === categoryState.current)
            if (selectedCategory) {
                setinitialValues({
                    id: selectedCategory.id,
                    name: selectedCategory.name,
                    desc: selectedCategory.desc,
                })
            }
        }
    }, [categoryState, dispatch])
    useEffect(() => {
        const categoryId = searchParams.get('category_id')
        const favoriteId = searchParams.get('favorite_id')
        if (!categoryId && !favoriteId && categoryState.list[0]) {
            setSearchParams({
                category_id: String(categoryState.list[0].id)
            })
        }else{
            dispatch(categoryIdChange(Number(categoryId)))
        }
        if (Number(categoryId) !== categoryState.current) {
            dispatch(detailReset())
        }
    }, [categoryState, dispatch, searchParams, setSearchParams])
    return (
        <>
            <Modal open={deleteFormOpen} onOk={onDelete} title='删除文件夹' children='确认删除此图片文件夹？' cancelText='取消' onCancel={() => setDeleteFormOpen(false)} />
            <CategoryFormModal name='create' open={createFormOpen} onOK={onCreate} onCancel={() => setCreateFormOpen(false)} title='创建文件夹' />
            {updateFormOpen && <CategoryFormModal name='update' open={updateFormOpen} onOK={onUpdate} onCancel={() => setUpdateFormOpen(false)} title='编辑文件夹' initialValues={initialValues} />}
            <UserMenuItem
                icon={<PlusCircleOutlined />}
                onClick={() => setCreateFormOpen(true)}
            >
                新建图片分类
            </UserMenuItem>
            <UserMenu
                actions={actions}
                actionIcon={<MoreOutlined />}
                defaultSelectedKey={searchParams.get('category_id') || '0'}
                selectedKey={categoryState.current?.toString()}
                style={{ height: '100%' }}
                items={items}
                onClick={(e) => {
                    setSearchParams({
                        category_id: e.key
                    })
                }}
            />
        </>
    )
}

export default UserCategoryMenu